#include "../RpcServer.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/service.h>

using namespace yhaida;
using namespace yhaida::rpc;



RpcServer::RpcServer(EventLoop *loop,
                     const InetAddress &listenAddr)
    : _server(loop, listenAddr)
{
    _server.setConnectionCallback(
        std::bind(&RpcServer::onConnection, this, _1));
    // server_.setMessageCallback(
    //     std::bind(&RpcServer::onMessage, this, _1, _2, _3));
}
void RpcServer::registerService(::google::protobuf::Service *service)
{ 
    const google::protobuf::ServiceDescriptor *desc = service->GetDescriptor();
    _services[desc->full_name()] = service;
}
void RpcServer::start()
{
    _server.start();
}

void RpcServer::onConnection(const TcpConnectionPtr &conn)
{
    LOG_INFO << "RpcServer - " << conn->peerAddress().toHostPort() << " -> "
             << conn->localhostAddress().toHostPort() << " is "
             << (conn->connected() ? "UP" : "DOWN");
    if (conn->connected())
    {
        RpcChannelPtr channel(new RpcChannel(conn));
        //将server注册的服务拷贝到channel
        channel->setServices(&_services);
        //为每个tcp连接指派message函数
        conn->setMessageCallback(
            std::bind(&RpcChannel::onMessage, get_pointer(channel), _1, _2, _3));
        conn->setContext(channel);
    }
    else
    {
        conn->setContext(RpcChannelPtr());
    }
}

// void RpcServer::onMessage(const TcpConnectionPtr& conn,
//                           Buffer* buf,
//                           Timestamp time)
// {
//   RpcChannelPtr& channel = boost::any_cast<RpcChannelPtr&>(conn->getContext());
//   channel->onMessage(conn, buf, time);
// }